package JDBC.Day05;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 *  测试JDBC工具类
 */
public class TestDemo {
    public static void main(String[] args) {
        List<Student> list = findAll();
        for (Student student : list) {
            System.out.println(student);
        }
        System.out.println(list.size());
    }

    public static List<Student> findAll() {
        //1. 获取连接对象
        //2. 创建执行sql的对象
        //3. 定义sql语句
        //4. 执行sql
        //5. 遍历结果集

        Connection conn = null;
        Statement stmt = null;
        ResultSet resultSet = null;
        List<Student> stuList = null;
        try {
            conn = JDBCUtils.getConnection();
            stmt = conn.createStatement();
            String sql = "SELECT * FROM student";
            resultSet = stmt.executeQuery(sql);
            stuList = new ArrayList<>();
            Student stu = null;

            while(resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String gender = resultSet.getString("gender");
                String birthday = resultSet.getString("birthday");
                String inser_time = resultSet.getString("insert_time");
                String address = resultSet.getString("address");
                // 创建对象并赋值
                stu = new Student();
                stu.setId(id);
                stu.setName(name);
                stu.setGender(gender);
                stu.setBirthday(birthday);
                stu.setInsert_time(inser_time);
                stu.setAddress(address);
                // 装载集合
                stuList.add(stu);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(resultSet, stmt, conn);
        }
        return stuList;
    }
}
